<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="1400" destroy-on-close :close-on-press-escape="mode != 'show' ? false : true"
             @closed="$emit('closed')" align-center>
    <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
      <el-row :gutter="1">
        <el-col :span="6">
          <el-form-item :label="$t('finance.paynum')" prop="pay_code">
            <el-input v-model="form.pay_code" :placeholder="$t('all.enter')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('procure.apply.name')" prop="supplier_id">
            <el-select v-model="form.supplier_id" :placeholder="$t('all.select')" filterable clearable>
              <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('finance.paydate')" prop="business_date">
            <el-date-picker v-model="form.business_date" type="date" :placeholder="$t('all.select')" style="width: 100%;" :value-format="'YYYY-MM-DD'"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="12">
        <el-form-item :label="$t('finance.pay')" prop="detail">
          <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" :placeholder="$t('all.noData')" height="180" show-summary @sons="accInput">
            <el-table-column :label="$t('finance.account')" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.settlement_id" :placeholder="$t('all.select')" filterable>
                  <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('procure.order.paymoney')" prop="money" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.money" :placeholder="$t('procure.order.paymoney')" @input="accInput"></el-input>
              </template>
            </el-table-column>
          </sc-form-table>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('finance.payorder')" prop="accounts_all">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="checkOrder">{{$t('finance.selectreceiveorder')}}</el-button>
          <sc-form-table ref="table" v-model="form.accounts_all" :addTemplate="accounts_all" :placeholder="$t('all.noData')" height="300" hideAdd show-summary @sons="orderInput">
            <el-table-column :label="$t('finance.businessdate')" prop="business_date" align="center"></el-table-column>
            <el-table-column :label="$t('finance.orderdate')" prop="contract_code" align="center"></el-table-column>
            <el-table-column :label="$t('finance.businesstype')" prop="type" align="center">
              <template #default="scope">
                {{scope.row.type == 1?$t('finance.producein'):scope.row.type == 2?$t('finance.producereturn'):$t('finance.other')}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('finance.dentall')" prop="money" align="center"></el-table-column>
            <el-table-column :label="$t('finance.paidalll')" prop="pay_money" align="center"></el-table-column>
            <el-table-column :label="$t('finance.meet')" prop="only_money" align="center"></el-table-column>
            <!-- <el-table-column label="当前欠款" prop="only_money" align="center"></el-table-column> -->
            <el-table-column :label="$t('procure.order.accountmoney')" prop="money" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.money" :placeholder="$t('procure.order.accountmoney') + ('(RMB)')" clearable @input="orderInput"></el-input>
              </template>
            </el-table-column>
          </sc-form-table>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('all.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('all.remark')" type="textarea"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('all.attachment')" prop="enclosure">
          <sc-upload-file v-model="form.enclosure" :limit="1">
            <el-button type="primary" icon="el-icon-upload">{{$t('all.selectattachment')}}</el-button>
          </sc-upload-file>
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">{{$t('all.cancel')}}</el-button>
      <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">{{$t('all.save')}}</el-button>
    </template>
  </el-dialog>
  <collection v-if="dialog.detail" ref="detailDialog" @success="handleSuccess" @closed="dialog.detail = false" :query="{supplier_id:this.form.supplier_id}"></collection>
</template>

<script>
import Collection from './collection.vue'

export default {
  components: {
    Collection,
  },
  emits: ['success', 'closed'],
  data() {
    return {
      mode: "add",
        titleMap: {
            add: this.$t('all.add'),
            edit: this.$t('all.edit'),
            show: this.$t('all.show')
      },
      visible: false,
      isSaveing: false,
      dialog: {
        detail: false,
      },
      form: {
        business_date: this.moment().format('YYYY-MM-DD'),
        pay_code: "",
        supplier_id: "",
        money: "",
        remark: "",
        enclosure: "",
        status: 1,
        accounts_all: [],
        detail: [],
      },
      addTemplate: {},
      accounts_all: {},
      accountList: [],    //账户
      applyList: [],     //客户
      countorder: "",
    }
  },
  mounted() {
    this.getAccount()
    this.getApply()
  },
  methods: {
    //显示
    open(mode = 'add') {
      this.mode = mode;
      this.visible = true;
      return this
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          if (this.form.money != this.countorder) {
            this.$alert("本次付款金额与单据金额不相等，请确认", this.$t('all.prompt'), {type: "error"})
          } else {
            this.isSaveing = true;
            var res = await this.$API.finance.fuorder.add.post(this.form);
            this.isSaveing = false;
            if (res.code == 1) {
              this.$emit('success', this.form, this.mode)
              this.visible = false;
              this.$message.success(this.$t('all.yes'))
            } else {
              this.$alert(res.message,this.$t('all.prompt'), {type: "error"});
            }
          }
        }
      })
    },
    //表单注入数据
    async setData(data) {
      this.form.id = data.id
      var res = await this.$API.finance.fuorder.detail.get({id: data.id});
      this.form.supplier_id = res.data.supplier_id
      this.form.pay_code = res.data.pay_code
      this.form.business_date = res.data.business_date
      this.form.remark = res.data.remark
      this.form.enclosure = res.data.enclosure
      this.form.status = res.data.status
      this.form.money = res.data.money
      this.form.detail = res.data.detail
      let array = []
      res.data.accounts.map(item => {
        array.push({
          business_date: item.accounts && item.accounts.business_date,
          contract_code: item.accounts && item.accounts.purchase && item.accounts.purchase.code,
          all_money: item.accounts && item.accounts.money,
          only_money: item.accounts && item.accounts.only_money,
          pay_money: item.accounts && item.accounts.pay_money,
          money: item.money,
          type: item.accounts && item.accounts.type,
        })
      })
      this.form.accounts_all = array
    },
    // 账号
    async getAccount() {
      var res = await this.$API.finance.account.all.get();
      this.accountList = res.data;
    },
    // 客户
    async getApply() {
      var res = await this.$API.apply.apply.all.get();
      this.applyList = res.data;
    },
    checkOrder() {
      if (this.form.supplier_id == '') {
        this.$message.error(this.$t('all.select') + ' ' + this.$t('procure.apply.apply'))
      } else {
        this.dialog.detail = true
        this.$nextTick(() => {
          this.$refs.detailDialog.open('add')
        })
      }
    },
    handleSuccess(data) {
      let array = []
      data.map(item => {
        array.push({
          accounts_id: item.id,
          business_date: item.business_date,
          contract_code: item.purchase && item.purchase.code,
          all_money: item.money,
          pay_money: item.pay_money,
          only_money: item.only_money,
          remark: item.remark,
          money: item.only_money,
          type: item.type,
        })
      })
      let existingIds = this.form.accounts_all.map(item => item.accounts_id);
      for (let i = array.length - 1; i >= 0; i--) {
        if (existingIds.includes(array[i].accounts_id)) {
          array.splice(i, 1);
        }
      }
      this.form.accounts_all = [...this.form.accounts_all, ...array]
      this.orderInput()
    },
    accInput() {
      let count_price = 0
      this.form.detail.map(item => {
        if (item.money) {
          count_price = Number(count_price) + Number(item.money)
        }
      })
      this.form.money = count_price
    },
    orderInput() {
      let count_price = 0
      this.form.accounts_all.map(item => {
        if (item.money) {
          count_price = Number(count_price) + Number(item.money)
        }
      })
      this.countorder = count_price
    },
  }
}
</script>

<style>
</style>
